package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrdersMapper ordersMapper;

    @Scheduled(cron = "0 * * * * ?")
    public void processTimeoutOrder() {

        Integer pendingPayment = Orders.PENDING_PAYMENT;
        LocalDateTime localDateTime = LocalDateTime.now().minusMinutes(15);
        List<Orders> list = ordersMapper.searchStatusBy(pendingPayment, localDateTime);
        if (list == null || list.size() < 0) {
            return;
        }
        for (Orders orders : list) {
            orders.setStatus(Orders.CANCELLED);
            orders.setCancelReason("订单超时未支付");
            orders.setCancelTime(localDateTime.now());
            ordersMapper.update(orders);
        }
    }

    @Scheduled(cron = "0 19 11 * * ?")
    public void processDeliveryOrder() {
        Integer pendingPayment = Orders.DELIVERY_IN_PROGRESS;
        LocalDateTime localDateTime = LocalDateTime.now().minusHours(1);
        List<Orders> list = ordersMapper.searchStatusBy(pendingPayment, localDateTime);
        if (list == null || list.size() < 0) {
            return;
        }
        for (Orders orders : list) {
            orders.setStatus(Orders.COMPLETED);
            orders.setDeliveryTime(LocalDateTime.now());
            ordersMapper.update(orders);
        }
    }

    @Scheduled(cron = "0 */1 * * * ?")
    public void testTask() {
        log.info(LocalDateTime.now().toString());

    }
}